package mtbldomain.presentation.metricview;

import java.util.List;

import mtbldomain.presentationmodel.metricview.MetricViewPresentationModel;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import domain.DomainFactory;
import domain.Entity;
import domain.Metric;
import domain.SystemVersion;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class MetricView extends ViewPart {
	public static final String ID = "mtbldomain.presentation.metricview.MetricView"; 
	
	private TreeViewer viewer;
	private Tree tree;
	private DrillDownAdapter drillDownAdapter;
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
	private MetricViewPresentationModel metricViewPresentationModel = MetricViewPresentationModel.getMetricViewPresentationModel();

	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	public class EntityTreeContentProvider 	implements IStructuredContentProvider, ITreeContentProvider {
		Entity invisibleRoot = null;
		
		public Object[] getChildren(Object parentElement) {
			Entity entity = (Entity) parentElement;
			return entity.getEntity().toArray();			
		}
		
		public Object getParent(Object element) {
			Entity entity = (Entity) element;
			return entity.getParent();
		}
		
		public boolean hasChildren(Object element) {	
			return ((Entity) element).getEntity().size() > 0;

		}
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			if (parent.equals(getViewSite())) {
				if (invisibleRoot==null) initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}
		private void initialize() {
			invisibleRoot = DomainFactory.eINSTANCE.createEntity();
			Entity entityRoot = DomainFactory.eINSTANCE.createEntity();
			entityRoot.setName("System History");
			entityRoot.setKind(-1);
			entityRoot.setParent(invisibleRoot);
			
			List<SystemVersion> systemVersionList = metricViewPresentationModel.getSystemHistory().getSystemVersion();
			
			for (SystemVersion systemVersion : systemVersionList) {
				entityRoot.getEntity().add(systemVersion.getProjectEntity());
			}
			invisibleRoot.getEntity().add(entityRoot);
		}
	}
	
	class EntityTreeLabelProvider extends LabelProvider implements ITableLabelProvider{

		public String getText(Object obj) {
			if(((Entity)obj).getKind()==Entity.PROJECT_ENTITY_KIND)
				return "Project Release " + ((Entity)obj).getRevisionNumber();
			else
				return ((Entity)obj).getName().toString();

		}

		@Override
		public Image getColumnImage(Object element, int columnIndex) {
			if(columnIndex == 0){
				String imageKey = ISharedImages.IMG_OBJ_ADD;

				if(((Entity)element).getKind()==Entity.PROJECT_ENTITY_KIND){
					imageKey = IDE.SharedImages.IMG_OBJ_PROJECT;
				}
				if(((Entity)element).getKind()==Entity.PACKAGE_ENTITY_KIND){
					imageKey = ISharedImages.IMG_OBJ_FOLDER;
				}
				if(((Entity)element).getKind()==Entity.CLASS_ENTITY_KIND){
					imageKey = ISharedImages.IMG_OBJ_FILE;
				}
				return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
			}
			return null;
		}
		@Override
		public String getColumnText(Object element, int columnIndex) {

			if(columnIndex==0){
				if(((Entity)element).getKind()==Entity.PROJECT_ENTITY_KIND){
					return "Project Release " + ((Entity)element).getRevisionNumber();
				}
				return ((Entity)element).getName();
			}	
			else{
				for(int i=1; i<= tree.getColumnCount(); i++){
					if(columnIndex == i){
						String metriColumnName = tree.getColumn(i).getText();
						List<Metric> metricList = ((Entity)element).getMetric();
						for (Metric metric : metricList) {
							if(metric.getShortName().equals(metriColumnName)){
								return metric.getValue().toString();
							}
						}
					}
				}
			}	
			return null;
		}
	}
	
	
	
	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public MetricView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		
		viewer.setContentProvider(new EntityTreeContentProvider());
		viewer.setLabelProvider(new EntityTreeLabelProvider());
		
		viewer.setSorter(new NameSorter());
		
		viewer.setInput(getViewSite());
		
		tree = viewer.getTree();
		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);
		
		createColumns(tree);

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "br.pucrio.les.systemhistory.mtblreader.editor.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void createColumns(Tree tree) {
		List<String> metricNameList = metricViewPresentationModel.getMetricList();
		if(!metricNameList.isEmpty()){
			TreeColumn objectFirstColumn = new TreeColumn(tree, SWT.NONE);
			objectFirstColumn.setText("");
			objectFirstColumn.setResizable(true);
			objectFirstColumn.setWidth(250);
			for (String metricName : metricNameList) {
				TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
				objectColumn.setText(metricName);
				objectColumn.setResizable(true);
				objectColumn.setWidth(95);
				
			}
		}
		
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				MetricView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				showMessage("Double-click detected on "+obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Sample View",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
	
	public void openMetricView() {
		try {
			@SuppressWarnings("unused")
			IViewPart viewPart = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
		
	}
}